import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/stores/user'

// 统一的带令牌请求数据方法

const instance = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器：添加Authorization头
instance.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器：已处理响应失败情况，直接返回响应数据
instance.interceptors.response.use(
  res => {
    const result = res.data
    if (result.code === 0) {
      return result.data
    } else {
      ElMessage.error(result.message || '请求失败')
      return Promise.reject(result)
    }
  },
  err => {
    ElMessage.error(err.response?.data?.message || '网络错误')
    return Promise.reject(err)
  }
)

export default instance // 默认导出，导入时可使用任意名字，比如：import api from '@/api/index'


